package titt.io.socket.in;

import java.io.BufferedInputStream;
import java.io.InputStream;

import titt.TITTValues;
import titt.io.reader.util.LineReader;

public class TITTInputStreamImpl implements TITTInputStream {
	
	private final InputStream in;
	private LineReader lr = null;
	
	public TITTInputStreamImpl(InputStream in) {
		this.in = in instanceof BufferedInputStream? in : new BufferedInputStream(in); 
	}	

	@Override
	public InputStream asStream() {
		return in;
	}

	@Override
	public void close() throws Exception {
		in.close();
	}

	@Override
	public void read(byte[] buffer) throws Exception {
		int bytesRead = 0, totalBytesRead = 0;

		boolean done = false;

		while(!done) {
			bytesRead = in.read(buffer, totalBytesRead, buffer.length - totalBytesRead);
			
			if(bytesRead == -1)
				throw new Exception("premature return from read (not enough bytes)");

			totalBytesRead += bytesRead;
			done = totalBytesRead == buffer.length;
		}
	}

	@Override
	public byte[] readLine() throws Exception {
		if(lr == null) lr = new LineReader(in, TITTValues.HTTP_NEWLINE);
		return lr.readLine();
	}
	
	@Override
	public byte[] readFully() throws Exception {
		byte[] b = new byte[in.available()];
		read(b);
		return b;
		
	}

}
